package com.newland.boss1.zxy.monitor;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : zhangxuyuan
 * @Project: springbootprometheus
 * @Package com.newland.boss1.zxy.monitor
 * @date Date : 2021年03月15日 10:20
 */
@Component
@Aspect
public class GaugesMonitor {

    @Autowired
    MeterRegistry meterRegistry;

    AtomicInteger gauge;

    @PostConstruct
    void construct()
    {
        gauge = meterRegistry.gauge("zxy-gauges",new AtomicInteger(0));
    }


    @Pointcut("@annotation(com.newland.boss1.zxy.monitor.GaugesMetric)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable
    {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        GaugesMetric annotation = method.getAnnotation(GaugesMetric.class);
       if("login".equals(annotation.type()))
       {
           //登录时在线用户量++
           gauge.getAndIncrement();
       }
       else{
           //登出后在线用户--
           gauge.getAndDecrement();
       }
        return joinPoint.proceed();

    }
}
